#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021-12-30 10:03:23
# @Author  : khz_mac
# @Site    :
# @File    : __init__.py.py
# @Software: ce9nt

"""
源码来自CSDN博主“挣扎的蓝藻”，已授权了。
博主网站地址：https://lanzao.blog.csdn.net/
源码文章地址：https://lanzao.blog.csdn.net/article/details/121072025

J:\_ALL\CODE\venv\py386_automate\Scripts\python.exe .\auto_shipinhao.py      eyJqSWQiOiAiNzAyMTEyNDkzMzM2NzM4NTM0NiIsICJteVRpdGxlQ24iOiAiXHU1YzBmXHU2MTY3XHU1NDFiXHU4ZDg1XHU1ZjNhY29zIFx1NjYyZlx1NTkyOVx1NGY3Zlx1NTU5NH5+fiIsICJteVRhZ3NDbiI6ICIjY29zcGxheSAjXHU1YzBmXHU1OWQwXHU1OWQwICNcdTVjMGZcdTYxNjdcdTU0MWIifQ==

"""


import os
import sys
import time
import base64
import types
import json
import pathlib
import random


def publish_shipinhao(param):
    '''
    作用：发布微信视频号
    '''
    import selenium
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys

    #     time.sleep(10)
    options = webdriver.ChromeOptions()
    # options.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
    # options.binary_location = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
    options.add_argument(r'--user-data-dir=J:\\_ALL\\chrome--user-data-dir\\公众号\\浏览器登录\\20000-爬虫分析')
    # didable "Chrome is being controled by an automated test software"
    options.add_argument('disable-infobars')
    #     options.add_argument("--profile-directory=Default")
    #     options.add_argument("--disable-extensions")
    #     options.add_experimental_option("debuggerAddress", "127.0.0.1:5003")
    #     options.add_argument("enable-automation")
    #     options.add_argument("--headless")
    #     options.add_argument("--window-size=1920,1080")
    #     options.add_argument("--no-sandbox")
    #     options.add_argument("--disable-extensions")
    #     options.add_argument("--dns-prefetch-disable")
    #     options.add_argument("--disable-gpu")
    driver = webdriver.Chrome(executable_path=r'J:\_ALL\CODE\venv\py386_automate\Scripts\chromedriver.exe', options=options)

    # 进入微信视频号创作者页面，并上传视频
    driver.get("https://channels.weixin.qq.com/post/create")
    time.sleep(2)
    driver.find_element_by_xpath('//input[@type="file"]').send_keys(param.get_path_video())

    # 等待视频上传完成
    # 检查一：等待video标签出现
    while True:
        time.sleep(3)
        try:
            video = driver.find_element_by_tag_name('video')
            if video:
                break
        except Exception as e:
            print("视频还在上传中···")

    print("视频已上传完成！")

    # 输入视频描述
    driver.find_element_by_xpath('//*[@data-placeholder="添加描述"]').send_keys(param.get_title())

    # 添加位置
    driver.find_element_by_xpath('//*[@class="position-display-wrap"]').click()
    time.sleep(2)
    driver.find_element_by_xpath('//*[text()="不显示位置"]').click()

    # 扩展链接
    links = [
        'https://mp.weixin.qq.com/s?__biz=MzAxNDY4MTY0MQ==&mid=2648031418&idx=1&sn=84152bdeed1de71608ccdd1a1c0665b8&chksm=83aef3fcb4d97aea51fc950dd70c8fcd7faf6ec331973fbe3ba5c5607ebc5d71d5e0dabbfdd1&token=1555776630&lang=zh_CN#rd',
        'https://mp.weixin.qq.com/s?__biz=MzAxNDY4MTY0MQ==&mid=2648031471&idx=2&sn=c30edd218be996fc4cfad70b62bd784d&chksm=83aef3a9b4d97abf0c91c2e2c189a07cb11eae1db57ba3d4bf3563356d02241387d7290d52c3&token=1555776630&lang=zh_CN#rd',
        'https://mp.weixin.qq.com/s?__biz=MzAxNDY4MTY0MQ==&mid=2648032742&idx=1&sn=7640c5c17f13e6919daad00f3d2e9e0f&chksm=83aef6a0b4d97fb643303ccd00c6996456b765badb8c337bc351528f858c145385f08cb33da6&token=1555776630&lang=zh_CN#rd',
        'https://mp.weixin.qq.com/s?__biz=MzAxNDY4MTY0MQ==&mid=2648031044&idx=1&sn=c8652890b5db3625315933fbf05cc682&chksm=83ae8c02b4d905148d44789dae21a7a1490cb10f8565408c93b175f92cc9ced57e8934824805&token=1555776630&lang=zh_CN#rd',
        'https://mp.weixin.qq.com/s?__biz=MzAxNDY4MTY0MQ==&mid=2648031043&idx=1&sn=3794de3647cd4260794c14691749f462&chksm=83ae8c05b4d905136df7bca061788a0f279532f0b073a471621dd0c19d479df7d13b2412f5c2&token=1555776630&lang=zh_CN#rd',
        'https://mp.weixin.qq.com/s?__biz=MzAxNDY4MTY0MQ==&mid=2648031037&idx=1&sn=e813be758e5fa29c63f3ce1ad6651302&chksm=83ae8c7bb4d9056d1b2ec88d9c73386d76b8d2f7e5fa23d2b3fd5064ae3b5db335e7ac39a026&token=1555776630&lang=zh_CN#rd',
        'https://mp.weixin.qq.com/s?__biz=MzAxNDY4MTY0MQ==&mid=2648031036&idx=2&sn=593f29a579a026cfccf53e61f3cf6033&chksm=83ae8c7ab4d9056c9271a92584bdcd5e4fdb326498a08f0ca7e664e0c63ba2cd4fdf4a0e0307&token=1555776630&lang=zh_CN#rd',
    ]
    link = random.choice(links)
    driver.find_element_by_xpath('//*[@placeholder="将公众号文章链接或红包封面链接粘贴在此处"]').send_keys(link[:-1])
    time.sleep(2)
    driver.find_element_by_xpath('//*[@placeholder="将公众号文章链接或红包封面链接粘贴在此处"]').send_keys(link[-1])

    # 人工进行检查并发布
    while True:
        if driver.current_url == 'https://channels.weixin.qq.com/platform/post/list':
            print('发布完成')
            break

        print('等待发布...')
        time.sleep(3)
    # # 点击发布
    # driver.find_element_by_xpath('//*[text()="发表"]').click()

    return 0


class VideoParam:
    """
    从java后台传过来的视频参数
        param_j         {"jId": "7021124933367385346", "myTitleCn": "小慧君超强cos 是天使喔~~~", "myTagsCn": "#cosplay #小姐姐 #小慧君"}
                        {"jId": "7021124933367385346", "myTitleCn": "\u5c0f\u6167\u541b\u8d85\u5f3acos \u662f\u5929\u4f7f\u5594~~~", "myTagsCn": "#cosplay #\u5c0f\u59d0\u59d0 #\u5c0f\u6167\u541b"}
        param_b64       eyJqSWQiOiAiNzAyMTEyNDkzMzM2NzM4NTM0NiIsICJteVRpdGxlQ24iOiAiXHU1YzBmXHU2MTY3XHU1NDFiXHU4ZDg1XHU1ZjNhY29zIFx1NjYyZlx1NTkyOVx1NGY3Zlx1NTU5NH5+fiIsICJteVRhZ3NDbiI6ICIjY29zcGxheSAjXHU1YzBmXHU1OWQwXHU1OWQwICNcdTVjMGZcdTYxNjdcdTU0MWIifQ==
    """
    def __init__(self, param_b64):
        # base64解密
        param_j = json.loads(base64.b64decode(param_b64))
        print(param_j)

        # 解析参数
        self.param = types.SimpleNamespace(**param_j)

        self.path_root = r'J:/_ALL/CODE/gitee/constellations/pig-ui/public/_tiktok_res/'

    def get_title(self):
        """拼接 myTitleCn myTagsCn"""
        return '{} {}'.format(self.param.myTitleCn, self.param.myTagsCn)

    def get_path_video(self):
        return '{}video/{}.mp4'.format(self.path_root, self.param.jId)

    def get_path_cover(self):
        return '{}cover/{}.jpg'.format(self.path_root, self.param.jId)


def test_selenium():
    import time
    import selenium
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys

    # 设置user-data-dir等参数
    options = webdriver.ChromeOptions()
    options.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
    options.add_argument(r'--user-data-dir=G:\\_ALL\\chrome--user-data-dir\\公众号\\浏览器登录\\20000-爬虫分析')
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(executable_path=r'J:\_ALL\CODE\venv\py386_automate\Scripts\chromedriver.exe', options=options)
    #     driver.maximize_window()
    driver.get('http://www.baidu.com')
    time.sleep(1)
    search_input = driver.find_element_by_css_selector('input#kw')
    search_input.send_keys('python')
    time.sleep(1)
    submit = driver.find_element_by_css_selector('input#su')
    submit.click()
    time.sleep(1)
    print(driver.current_url)
    results = driver.find_elements_by_css_selector('h3 > a')
    for result in results:
        print(result.text)


def main():
#     return test_selenium()

    # 处理参数
    if len(sys.argv) < 2:
        print('len(sys.argv) < 2')
        return 1

    param = VideoParam(sys.argv[1])
    print(param.get_title(), param.get_path_video(), param.get_path_cover())

    # 开始执行视频发布
    return publish_shipinhao(param)


if __name__ == "__main__":
    print("------------------    Enter __main__    ------------------")

    print(u"[Current work directory is : ]\t" + os.getcwd())
    print(u"[Current process ID is : ]\t" + str(os.getpid()))
    print("\n")
    ret = main()

    print("------------------    Leave __main__    ------------------")

    exit(ret)
